<template>
  <el-menu-item v-if="theOnlyOneChild && !theOnlyOneChild.children" :index="resolvePath(theOnlyOneChild.path)">
    <!-- 图标 -->
    <div class="sub-menu-icon" v-if="theOnlyOneChild.meta?.icon">
      <i
        v-if="typeof theOnlyOneChild.meta.icon === 'string' && theOnlyOneChild.meta.icon.includes('iconfont')"
        class="el-icon"
        :class="theOnlyOneChild.meta.icon"></i>
      <el-icon v-else>
        <component :is="theOnlyOneChild.meta.icon" />
      </el-icon>
    </div>
    <!-- 这里的title标签是为了解决el-menu-item的默认样式问题 -->
    <template v-if="theOnlyOneChild.meta?.title" #title>
      <span>{{ theOnlyOneChild.meta.title }}</span>
    </template>
  </el-menu-item>
  <el-sub-menu v-else :index="resolvePath(item.path)" teleported>
    <template v-if="item.meta?.title" #title>
      <!-- 图标 -->
      <div class="sub-menu-icon" v-if="item.meta?.icon">
        <i
          v-if="typeof item.meta.icon === 'string' && item.meta.icon.includes('iconfont')"
          class="el-icon"
          :class="item.meta.icon"></i>
        <el-icon v-else>
          <component :is="item.meta.icon" />
        </el-icon>
      </div>
      <span>{{ item.meta.title }}</span>
    </template>
    <sidebar-item
      v-for="child in showingChildren"
      :key="child.path"
      :item="child"
      :base-path="resolvePath(child.path)"></sidebar-item>
  </el-sub-menu>
</template>
<script setup lang="ts">
import { computed } from "vue";
import path from "path-browserify";
import { type RouteRecordRaw } from "vue-router";
defineOptions({
  name: "SidebarItem"
});
interface Props {
  item: RouteRecordRaw;
  basePath?: string;
}
const props = withDefaults(defineProps<Props>(), {
  basePath: ""
});
/** 显示的子菜单 */
const showingChildren = computed(() => {
  return props.item.children?.filter((child) => !child.meta?.hidden) ?? [];
});
/** 显示的子菜单数量 */
const showingChildNumber = computed(() => {
  return showingChildren.value.length;
});
/** 唯一的子菜单项 */
const theOnlyOneChild = computed(() => {
  const number = showingChildNumber.value;
  switch (true) {
    case number > 1:
      return null;
    case number === 1:
      return showingChildren.value[0];
    default:
      return { ...props.item, path: "" };
  }
});
/** 解析路径 */
const resolvePath = (routePath: string) => {
  const httpReg = /^http(s?):\/\//;
  if (httpReg.test(routePath) || httpReg.test(props.basePath)) {
    return routePath || props.basePath;
  } else {
    return path.resolve(props.basePath, routePath);
  }
};
</script>
<style scoped lang="scss"></style>
